<template>
  <div class="publish-container">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{path: '/page/book'}">柚子抽屉</el-breadcrumb-item>
      <el-breadcrumb-item v-if="isShow">创建文档</el-breadcrumb-item>
      <el-breadcrumb-item v-else-if="isEdit">编辑文档</el-breadcrumb-item>
      <el-breadcrumb-item v-else>上传附件</el-breadcrumb-item>
    </el-breadcrumb>
      <el-card class="box-card" v-show="isShow">
        <el-form ref="form" :model="article" label-width="120px">
          <el-form-item label="文章标题">
            <el-input v-model="article.title"></el-input>
          </el-form-item>
          <el-form-item label="文章内容">
             <el-tiptap v-model="article.content" :extensions="extensions" height="600" placeholder="请输入文章内容"
          ></el-tiptap>
          </el-form-item>
          <el-form-item label="封面">
              <!-- 发布封面裁剪 -->
            <div class="cropper-app">
              <el-upload
                action="#"
                class="btn"
                drag
                :auto-upload="true"
                :show-file-list="false"
                :on-change="handleCrop"
                :before-upload="beforeAvatarUpload"
              >
                <img
                  class="Group-img"
                  v-if="loadingtext"
                  title="点击更换封面"
                  style="width: 100px; height: 100px"
                  :src="article.cover"
                />
                <el-button
                  plain
                  round
                  class="img-btn"
                  v-if="!loadingtext"
                  size="mini"
                  >添加封面</el-button
                >
              </el-upload>

              <!-- 剪裁组件弹窗 -->
              <cropperImage
                :dialogVisible="showCropper"
                :cropper-option="cropperOption"
                :file-size="fileSize"
                :cropper-style="cropperStyle"
                @close="showCropper = false"
                @uploadCropper="uploadImg"
              />
            </div>
          </el-form-item>
          <el-form-item label="文章类别">
            <el-input  type="text"  placeholder="请输入类别"  v-model="article.tag"  maxlength="2"  show-word-limit class="tag"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="warning" @click="onPublish">发表</el-button>
          </el-form-item>
        </el-form>
      </el-card>
      <el-card class="box-card"  v-show="isEdit">
        <el-form ref="form" :model="article" label-width="120px">
          <el-form-item label="文章标题">
            <el-input v-model="article.title"></el-input>
          </el-form-item>
          <el-form-item label="文章内容">
             <el-tiptap v-model="article.content" :extensions="extensions" height="600" placeholder="请输入文章内容"
          ></el-tiptap>
          </el-form-item>
          <el-form-item label="封面">
            <!-- 编辑封面裁剪 -->
            <div class="cropper-app">
              <el-upload
                action="#"
                class="btn"
                drag
                :auto-upload="true"
                :show-file-list="false"
                :on-change="handleCrop"
                :before-upload="beforeAvatarUpload"
              >
                <el-button class="img-btn" v-if="!loadingtext" size="mini"
                  >添加封面</el-button
                >
                <img
                  class="Group-img"
                  v-if="loadingtext"
                  title="点击更换封面"
                  style="width: 100px; height: 100px"
                  :src="article.cover"
                />
              </el-upload>

              <!-- 剪裁组件弹窗 -->
              <cropperImage
                :dialogVisible="showCropper"
                :cropper-option="cropperOption"
                :file-size="fileSize"
                :cropper-style="cropperStyle"
                @close="showCropper = false"
                @uploadCropper="uploadImg"
              />
            </div>
          </el-form-item>
          <el-form-item label="文章类别">
            <el-input type="text"  placeholder="请输入类别"  v-model="article.tag"  maxlength="2"  show-word-limit class="tag"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="warning" @click="onPublish">发表</el-button>
          </el-form-item>
        </el-form>
      </el-card>
      <el-card class="smallBox" v-show="isFile">
        <div slot="header" class="clearfix">
          <span>上传附件</span>
        </div>
        <form id="Formreset">
          <div class="file">
            <div class="fileNoShow"><input type="file" @input="inputFile" id="file-btn"></div>
            <div class="fileShow">
              <el-input placeholder="文件名称" :value="fileName">
              <el-button slot="append" @click="selectFile">选择文件</el-button>
            </el-input>
            </div>
          </div>
          <el-progress :percentage="progressBar" class="progressBar" v-show="isBar" color="#89e9cf" stroke-width="12"></el-progress>
          <el-button type="warning" @click="loadFile" :disabled="isBtn"  v-loading.fullscreen.lock="fullscreenLoading">上传附件</el-button>
        </form>
      </el-card>
  </div>
</template>

<script>
import cropperImage from '@/views/pageIn/mine/components/Copper.vue'
import request from '@/utils/api/request'
import { addArticle, lookDoc, updateDoc, updatImg } from '@/utils/api/library'
import {
  ElementTiptap,
  Doc,
  Text,
  Paragraph,
  Heading,
  Bold,
  Underline,
  Italic,
  Strike,
  ListItem,
  BulletList,
  OrderedList,
  Link,
  Iframe,
  CodeBlock,
  Blockquote,
  TodoItem,
  TodoList,
  TextAlign,
  FontSize,
  FontType,
  SelectAll,
  Fullscreen,
  Preview,
  TextHighlight,
  TextColor,
  FormatClear,
  Table,
  TableHeader,
  TableCell,
  TableRow,
  History,
  TrailingNode,
  HardBreak,
  HorizontalRule,
  LineHeight,
  Indent,
} from 'element-tiptap'
export default {
  name: '',
  components: {
    'el-tiptap': ElementTiptap,
    cropperImage
  },
  props: {
    lid: {
      required: true
    },
    docid: {
      required: true
    }
  },
  data () {
    return {
      // 裁剪数据
      cropperData: {},
      showCropper: false, // 显示裁剪弹窗
      canCropper: false,
      loadingtext: false,
      fileSize: 2, // 限制文件上传大小
      formate: new FormData(),
      cropperOption: {
        img: '',
        autoCropWidth: 300,
        autoCropHeight: 180
      },
      cropperStyle: {
        width: '600px',
        height: '300px'
      },
      // 编辑器的 extensions
      extensions: [
        new Fullscreen(),
        new Doc(),
        new Text(),
        new Paragraph(),
        new Heading({ level: 6 }),
        new Bold({ bubble: true }), // 在气泡菜单中渲染菜单按钮
        new Underline({ bubble: true, menubar: false }), // 在气泡菜单而不在菜单栏中渲染菜单按钮
        new Italic(),
        new Strike(),
        new ListItem(),
        new BulletList(),
        new OrderedList(),
        new Link(),
        new Iframe(),
        new CodeBlock(),
        new Blockquote(),
        new TodoItem(),
        new TodoList(),
        new TextAlign(),
        new FontSize(),
        new FontType(),
        new SelectAll(),
        new Preview(),
        new TextHighlight(),
        new TextColor(),
        new FormatClear(),
        new Table({ resizable: true }),
        new TableHeader(),
        new TableCell(),
        new TableRow(),
        new History(),
        new TrailingNode(),
        new HardBreak(),
        new HorizontalRule(),
        new LineHeight(),
        new Indent(),
      ],
      article: {
        title: '', // 文章标题
        content: '', // 文章内容
        cid: '周报',
        url: '...',
        cover: '',
        tag: '' // 文章类别标签(自定义)
      },
      file: null,
      dialogVisible: false,
      isShow: true,
      isEdit: false,
      isFile: false,
      nowDoc: null,
      isBar: false,
      isBtn: true,
      progressBar: 0,
      fileName: null
    }
  },
  created () {
    if (this.docid === '01') {
      this.isShow = true
      this.isFile = false
      this.isEdit = false
    } else if (this.docid === '02') {
      this.isFile = true
      this.isShow = false
      this.isEdit = false
    } else {
      this.isEdit = true
      this.isShow = false
      this.isFile = false
    }
    this.load()
  },
  methods: {
    // 点击弹出剪裁框
    handleCrop (file) {
      this.$nextTick(() => {
        if (this.canCropper) {
          this.cropperOption.img = window.URL.createObjectURL(file.raw)
          this.showCropper = this.canCropper
        }
      })
    },
    // 上传前校验
    beforeAvatarUpload (file) {
      const isJPG =
        file.type === 'image/jpeg' ||
        file.type === 'image/jpg' ||
        file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2 MB!')
      }
      // 校验通过后显示裁剪框
      this.canCropper = isJPG && isLt2M
      return false
    },
    // 自定义的图片提交事件
    uploadImg (f, data) {
      const formdata = new FormData()
      formdata.append('pic', f)
      this.loadingtext = true
      this.cropperData.iconUrl = data
      this.showCropper = false
      this.formate = formdata
      updatImg(formdata).then(res => {
        this.article.cover = res.data.name
      })
    },
    // 获取文章分类标签
    load () {
      if (this.docid !== '01' && this.docid !== '02') {
        lookDoc(this.docid).then(res => {
          this.article.content = res.data.data.content
          this.article.cover = res.data.data.cover
          this.article.title = res.data.data.docname
          this.article.tag = res.data.data.identity
          this.loadingtext = true
        })
      }
    },
    onPublish () {
      const data = {
        content: this.article.content,
        cover: this.article.cover,
        docname: this.article.title,
        identity: this.article.tag,
        creatorID: this.lid
      }
      if (!data.docname) {
        data.docname = '这是一篇文章'
      }
      if (!data.identity) {
        data.identity = '文档'
      }
      if (this.docid === '01') {
        addArticle(data).then(res => {
          if (res.data.code === 200) {
            this.$message({
              message: '发布文章成功',
              type: 'success'
            })
            this.$router.push('/page/book')
          }
        }).catch(() => {
          this.$message({
            message: '发布文章失败',
            type: 'error'
          })
        })
      } else if (this.docid === '02') {} else {
        updateDoc(data, this.docid).then(res => {
          if (res.data.code === 200) {
            this.$message({
              message: '编辑文章成功',
              type: 'success'
            })
            this.$router.push('/page/book')
          }
        }).catch(() => {
          this.$message({
            message: '编辑文章失败',
            type: 'error'
          })
        })
      }
    },
    selectFile () {
      document.getElementById("file-btn").click();
    },
    inputFile (e) {
      if (e.target.files[0].size > 10485760) {
        this.$message({
          type: "error",
          message: "文件大小不能超过10MB，请重新选择"
        })
        const filedom = document.getElementById('Formreset');
        filedom.reset(e.target.files[0])
      } else {
        this.isBtn = false
        this.file = e.target.files[0]
        this.fileName = this.file.name
      }
    },
    loadFile () {
      this.isBar = true
      this.isBtn = true
      const fd = new FormData()
      fd.append('file', this.file)
      const _this = this
      request({
        method: 'POST',
        url: `/UserLib/userAnnex?lid=${this.lid}`,
        data: fd,
        headers: {
          'Content-Type': "multipart/form-data"
        },
        // bug原因：this指向问题
        onUploadProgress: function (event) {
          _this.progressBar = event.loaded / event.total * 100 | 0
        }
      }).then((res) => {
        if (res.data.code === 200) {
          this.$message({
            message: '上传附件成功',
            type: 'success'
          })
          this.$router.push('/page/book')
        }
      }).catch(() => {
        this.$message({
          message: '上传附件失败',
          type: 'error'
        })
        this.isBar = false
      })
    }
  }
}

</script>

<style lang="less" scoped>
.box-card{
  margin-top: 20px;
  margin-bottom: 70px;
}
.smallBox{
  height: 600px;
  width: 65%;
  margin: 20px auto;
}
.file{
  position: relative;
  margin: 0 auto 40px;
  height: 40px;

}
.fileNoShow{
  // -moz-opacity:0;
  // -khtml-opacity: 0;
  // opacity: 0;
  position: absolute;
  z-index: -9;
}
.fileShow{
  width: 100%;
  position: relative;
  z-index: 9;
}
.tag{
  width: 200px;
}
.progressBar{
  margin-bottom: 40px;
  width: 100%;
}
#Formreset{
  margin: 10px 40px;
}
.clearfix{
  font-size: 26px;
}
.cropper-app {
  /deep/ .el-dialog {
    width: max-content;
    max-width: 860px;
    height: 520px;
  }
  /deep/ .el-image__inner {
    overflow: hidden;
    border-radius: 6px;
  }
  .img-btn {
    width: 100%;
    height: 100%;
    font-size: 28px;
    color: #aaa;
  }
  .img-btn:hover {
    opacity: 1;
    transition: 1.5s;
  }
  .Group-img {
    width: 100% !important;
    height: 100% !important;
  }
}
</style>
